Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Looping with both `var' and `i' simultaneously

    Hello,

    I want to loop over my variable list, but also be able to have a number `i' that reflects the loop iteration.
    Code:
    foreach var in varlist *{
    [command using loop iteration `i' and `var']
    }
    Is there a way to have both of these in the loop? Or another way to accomplish?

    All I know how to do is manually create a list of locals like this with the whole varlist:
    Code:
    local variable1 make
    local variable2 price 
    local variable3 mpg
    [...]
    Then loop with i = 1/n and variable`i'

    But is there a way to do this without making that local list manually?


    Thanks for any help!

    Reese

  • #2
    Code:
    local i = 0
    foreach var in varlist * {
       local ++i
       [command using loop iteration `i' and `var']
    }

    Comment


    • #3
      Perfect, thank you Mike!

      p.s. I'd like to learn more about use of "++", can you (or anyone else) direct me on where to look or what it's called?

      Comment


      • #4
        The output of help macro shows the syntax but doesn't say anything about what it does. You can find a description of "macro increment and decrement functions" in Sections 18.3.4 and 18.3.7 of the Stata User's Guide PDF included in your Stata installation and accessible from Stata's Help menu.

        Comment


        • #5
          Thanks William! That's exactly what I was looking for.

          Comment

          Working...
          X